package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

type ErpClass struct {
	Id        int64
	ClassName string
	ParentId  int64
	Pinyin    string
	Status    int
	CreatedAt int64
	UpdatedAt int64
	Level     int    `orm:"-"`
	Prefix    string `orm:"-"`
	Typeid    int
}

type ErpClassQueryParam struct {
	BaseQueryParam
	Filter string
}

func ErpClassStyle() map[int]string {
	style := make(map[int]string)
	style = map[int]string{10: "近视镜片", 20: "远视镜片", 30: "隐形眼镜", 40: "眼镜框架", 50: "其它", 60:"检查项目"}
	return style
}

func (a *ErpClass) TableName() string {
	return ErpCLassTableName()
}

func ErpCLassTableName() string {
	return TableName("erp_class")
}

func GetErpClassById(id int64) (*ErpClass, error) {

	r := new(ErpClass)
	err := orm.NewOrm().QueryTable(ErpCLassTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil
}

func ErpClassList(params *ErpClassQueryParam) map[string]interface{} {

	m := make(map[string]interface{})

	return m
}

func ErpClassLists() []*ErpClass {

	list := make([]*ErpClass, 0)

	orm.NewOrm().QueryTable(ErpCLassTableName()).All(&list)

	rest := make([]*ErpClass, 0)

	for _, item := range list {
		if item.ParentId == 0 {
			item.Level = 0
			item.Prefix = ""
			rest = append(rest, item)
			rest = ErpClassChildItem(item, list, rest)
		}
	}

	return rest
}

func ErpClassTree() []*ErpClass {

	list := make([]*ErpClass, 0)

	orm.NewOrm().QueryTable(ErpCLassTableName()).Filter("status", 1).All(&list)

	rest := make([]*ErpClass, 0)

	for _, item := range list {
		if item.ParentId == 0 {
			item.Level = 0
			item.Prefix = ""
			rest = append(rest, item)
			rest = ErpClassChildItem(item, list, rest)
		}
	}

	return rest
}

func ErpClassChildItem(cur *ErpClass, list, rest []*ErpClass) []*ErpClass {

	for _, item := range list {
		if item.ParentId == cur.Id {
			item.Level = cur.Level + 1
			item.Prefix = cur.Prefix + " |-- "
			rest = append(rest, item)
			rest = ErpClassChildItem(item, list, rest)
		}
	}

	return rest
}

func ErpClassAdd(a *ErpClass) (int64, error) {

	a.Pinyin = utils.ConvertPinyin(a.ClassName)
	a.Status = 1
	a.CreatedAt = time.Now().Unix()
	a.UpdatedAt = time.Now().Unix()

	return orm.NewOrm().Insert(a)
}

func (a *ErpClass) ErpClassEdit(fields ...string) error {

	a.Pinyin = utils.ConvertPinyin(a.ClassName)
	a.UpdatedAt = time.Now().Unix()

	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}

func ErpClassDel(id int64) error {

	var c ErpClass
	c = ErpClass{Id: id, Status: 2}

	orm.NewOrm().Read(&c)
	if c.Status == 1 {
		c.Status = 2
	} else {
		c.Status = 1
	}
	if _, err := orm.NewOrm().Update(&c, "status"); err != nil {
		return err
	}
	return nil
}
